package main

import (
	"fmt"
	"freechat-im/common"
	"freechat-im/config"
	"freechat-im/core"
	"freechat-im/support"
	"github.com/joho/godotenv"
	"github.com/sirupsen/logrus"
	"log"
	"net/http"
	"os"
	"path"
	"runtime"
	"strings"
)

// 变量：数据来源于环境变量
var (
	mode2 common.ModeStatus
)

func init() {
	fmt.Println("init ...")

	// 在 init 中计算并设置全局变量
	isCluster := strings.EqualFold(os.Getenv("mode"), "cluster")
	if isCluster {
		mode2 = common.Mode_Cluster
	} else {
		mode2 = common.Mode_Single
	}

	// 加载项目根目录的 .env 文件
	err := godotenv.Load()
	if err != nil {
		log.Fatalf("加载 .env 文件失败: %v", err)
	}

	InitAllConfig(mode2)
}

func main() {
	service := core.Start(int(mode2))

	http.HandleFunc("/ws", service.HandleWebSocket)

	logrus.Fatal(http.ListenAndServe(":7777", nil))
}

func InitAllConfig(mode common.ModeStatus) {
	isDev := strings.EqualFold(os.Getenv("env"), "dev")
	InitLogs(isDev)

	var redisProperties = &config.RedisProperties{
		Addr:     os.Getenv("REDIS_ADDR"),
		Password: os.Getenv("REDIS_PASSWORD"),
		DB:       1,
	}
	config.InitRedis(redisProperties)

	var mqProperties = &config.RabbitMQProperties{
		Username: os.Getenv("RABBITMQ_USERNAME"),
		Password: os.Getenv("RABBITMQ_PASSWORD"),
		Endpoint: os.Getenv("RABBITMQ_ENDPOINT"),
	}
	config.InitMQ(mqProperties)

	var properties = &config.Properties{
		GRpcAddr:       os.Getenv("GRPC_ADDR"),
		ZookeeperHosts: os.Getenv("ZOOKEEPER_HOSTS"),
	}
	config.InitGrpcClients(properties.GRpcAddr)

	if mode == common.Mode_Cluster {
		InitWithCluster(properties)
	}
}

func InitWithCluster(properties *config.Properties) {
	config.InitZookeeper(properties.ZookeeperHosts)

	support.RegisterNode()
	//启动Nats订阅
	support.StartSubscribe(core.SendMessage, core.GetService().SendToClient)
}

func InitLogs(debug bool) {
	//日志格式
	logrus.SetFormatter(&logrus.TextFormatter{
		ForceColors:     true,                  //显示颜色
		FullTimestamp:   true,                  // 完整时间
		TimestampFormat: "2006-01-02 15:04:05", // 时间格式
		CallerPrettyfier: func(f *runtime.Frame) (string, string) {
			filename := path.Base(f.File)
			//自定义你想要的格式
			return "", fmt.Sprintf("%s:%d", filename, f.Line)
		},
	})
	logrus.SetReportCaller(true) // 显示行号
	if debug {
		logrus.SetLevel(logrus.DebugLevel)
	} else {
		logrus.SetLevel(logrus.InfoLevel)
	}
}
